import os


def splitsql(file, nums,storepath):
    fd=open(file, encoding='utf-8')

    lines=fd.readlines()

    filename=os.path.basename(file).split(".")[0]
    # win默认桌面路径（未修改桌面路径）
    desktop=os.path.join(os.path.expanduser("~"), 'Desktop')
    if storepath == "":
        print("storepath is '',set storepath is default window desktop")
        storepath = desktop

    firstLine=lines[0];
    # print(firstLine)
    # print(len(lines))

    # 干掉第一行
    lines=lines[1:]
    # print(lines)

    allTempList=[]


    for i in range(int(len(lines)/nums+1)):
        j=i+1
        # tempname = "lang2\\" + filename + str(j) + '.sql'
        tempname=filename+str(j)+'.sql'
        # print(i)
        temp=lines[nums*i:nums*(i+1)]



        if len(temp)>0:
            temp[-1]=temp[-1].strip()[0:-1]+';\n\n'
            # print(temp)
            temp.insert(0, firstLine)
            allTempList+=temp


    file_write_obj=open(os.path.join(storepath, filename+'agg.sql'), 'w', encoding="utf-8")  # 新文件
    # file_write_obj.write(firstLine)  # 逐行写入
    for var in allTempList:
        print(var)
        # file_write_obj.write(firstLine)  # 逐行写入
        file_write_obj.write(var)  # 逐行写入
        # file_write_obj.write('\n')
    file_write_obj.close()

        # print(len(temp))
        # break


if __name__=='__main__':
    file='../../数据测试集/批处理sql到一个文件.sql'
    nums=2
    storepath='数据结果集'
    splitsql(file, nums,storepath)